<template>
  <BasicForm @register="registerForm" v-loading="loading" >
  
    <template #footer-action="{ model, field }">
      <a-button class="mr-5">重置</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </template>
  </BasicForm>
</template>
<script lang="ts" setup name="AppConfig">
  import { ref, nextTick, onMounted, watch } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { loginControllFormSchema } from "../data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import * as appApi from "/@/api/iam/app"
  const { createMessage, createConfirm } = useMessage()
  import { isString, isArray } from "/@/utils/is"

  const emit = defineEmits(["success", "register"])
  const rowId = ref("")
  const loading = ref(false)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: loginControllFormSchema,
    labelWidth: 145,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, sm: 24 },
  })

  const props = defineProps({
    data: { type: Object }
  })

  onMounted(() => {

  })

  
  watch(
    () => props.data,
    (data) => {
      nextTick(() => {
        initData(data)
      })
      
    }, 
    { immediate: true }
  )

  const initData = async (data) => {
    if (!data) {
      return
    }
    await resetFields()
    rowId.value = data.id
    setFieldsValue({ 
      ...data,
      completeFieldNameStr: isString(data.completeFieldNameStr) && data.completeFieldNameStr != '' ? data.completeFieldNameStr.split(',') : []
    })
  }

  async function handleSubmit() {
    try {
      let values = await validate()
      if (isString(values.completeFieldPlaces)) {
        values.completeFieldPlaces = values.completeFieldPlaces?.split(',').filter(e => e && e != '')
      }

      if (isString(values.completeFieldNameStr)) {
        values.completeFieldNameStr = values.completeFieldNameStr == '' ? null : values.completeFieldNameStr
      }

      const params = { ...values }
      delete params['footer-action']
      for(const key in params) {
        if (key.startsWith('divider')) {
          delete params[key]
        }
      }

      console.log("submit", params)
      loading.value = true
      await appApi.updateApp(params)
      emit("success", params)
      createMessage.success('保存成功')
    } finally {
      loading.value = false
    }
  }
</script>
